import type { ProFormInstance } from '@ant-design/pro-form';
import {
  DrawerForm,
  ProFormDependency,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { Col, Row } from 'antd';
import React, { useRef, useState } from 'react';

import { AreaGroupOptions, getAreaGroupCountrys } from '@/services/consts';
import * as isoCodes from '@/services/countryCodes';
import { EditableProTable, ProColumns } from '@ant-design/pro-components';

type FormProps = {
  visible: boolean;
  current: API.SmartModeConfig | undefined;
  onCancel: () => void;
  onSubmit: (values: API.SmartModeConfig) => Promise<void>;
};

const Form: React.FC<FormProps> = (props) => {
  const { visible, current, onCancel, onSubmit } = props;
  if (!visible) {
    return null;
  }

  let defaultCurrent: Partial<API.SmartModeConfig> | undefined = undefined;
  if (!current) {
    defaultCurrent = {
      status: true,
    };
  }

  const formRef = useRef<ProFormInstance>();

  const xrayGetFile = current?.xrayConfig?.map((item) => {
    item.id = item.ver;
    return item;
  });

  const [editableGeoKeys, setEditableGeoKeys] = useState<React.Key[]>(() =>xrayGetFile?.map((item) => item.id));
  const [geoDataSource, setGeoDataSource] = useState<readonly API.SmartModePolicy[] | undefined>(xrayGetFile);  

  const handleFormSubmit = async (record: API.SmartModeConfig) => {
    record.xrayConfig = geoDataSource ? geoDataSource.map((val) => val) : undefined;
    onSubmit(record);
  };
  
  const geoColumns: ProColumns<API.SmartModePolicy>[] = [
    {
      title: 'MD5码',
      dataIndex: 'md5',
      // width: 160,
      formItemProps: () => {
        return {
          rules: [
            { required: true, message: '请输入MD5码' },
          ],
        };
      },
    },
    {
      title: '文件地址',
      dataIndex: 'url',
      // width: 160,
      formItemProps: () => {
        return {
          rules: [
            { required: true, message: '请输入文件地址' },
          ],
        };
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 50,
    },
  ];

  return (
    <DrawerForm<API.SmartModeConfig>
      open={visible}
      autoFocusFirstInput
      width={800}
      title={`${current ? '编辑' : '添加'}智能模式配置`}
      initialValues={current ? current : defaultCurrent}
      formRef={formRef}
      //preserve={false}
      //trigger={<>{children}</>}
      onFinish={handleFormSubmit}
      drawerProps={{
        onClose: onCancel,
        //destroyOnClose: true,
        maskClosable: false,
      }}
    >
      <Row gutter={24}>
        <Col span={12}>
          <ProFormSelect
            name="areaGroup"
            label="地区分组"
            options={AreaGroupOptions}
            rules={[{ required: true, message: '请选择地区分组' }]}
          />
        </Col>
        <Col span={12}>
          <ProFormDependency name={['areaGroup']}>
            {({ areaGroup }) => {
              // formRef.current?.setFieldValue('contury', '');
              if (areaGroup) {
                const conturys = getAreaGroupCountrys(areaGroup);
                return (
                  <>
                    <ProFormSelect
                      name="contury"
                      label="国家地区"
                      options={conturys}
                    />
                  </>
                );
              }
              return <ProFormSelect name="contury" label="国家地区" />;
            }}
          </ProFormDependency>
        </Col>
        <Col span={12}>
          <ProFormDependency name={['areaGroup', 'contury']}>
            {({ areaGroup, contury }) => {
              let code = '';
              if (areaGroup || contury) {
                if (contury) {
                  code = isoCodes.getCodeByName(contury);
                } else {
                  code = isoCodes.getCodeByName(areaGroup);
                }
              }
              formRef.current?.setFieldValue('conturyCode', code);
              return <></>;
            }}
          </ProFormDependency>
          <ProFormText name="conturyCode" label="地区CODE" readonly />
        </Col>
        <Col span={12}>
          <ProFormSwitch name="status" label="状态" />
        </Col>
        <Col span={24}>
            <EditableProTable<API.SmartModePolicy>
              rowKey="id"
              locale={{ emptyText: '暂无数据' }}
              toolBarRender={false}
              columns={geoColumns}
              value={geoDataSource}
              onChange={setGeoDataSource}
              recordCreatorProps={{
                newRecordType: 'dataSource',
                position: 'bottom',
                record: () => ({
                  id: Date.now().toString(),
                  md5: '',
                  url:'http://'
                }),
              }}
              editable={{
                type: 'multiple',
                editableKeys: editableGeoKeys,
                actionRender: (row, config, defaultDom) => [
                  defaultDom.delete,
                ],
                onValuesChange: (record, recordList) => {
                  setGeoDataSource(recordList);
                },
                onChange: setEditableGeoKeys,
              }}
              pagination={false}
            />
        </Col>
        <Col span={24}>
          <ProFormTextArea
            name={['skipDomainConfig', 'content']}
            label="域名列表"
            fieldProps={{ rows: 30 }}
          />
        </Col>
        <Col span={24}>
          <ProFormTextArea name="remark" label="备注" />
        </Col>
      </Row>
    </DrawerForm>
  );
};

export default Form;
